package org.burning.crm.workbench.service.impl;

import org.apache.poi.ss.formula.functions.Count;
import org.burning.crm.commons.constants.Constant;
import org.burning.crm.commons.utils.DateUtils;
import org.burning.crm.commons.utils.UUIDUtils;
import org.burning.crm.settings.domain.User;
import org.burning.crm.workbench.domain.Contacts;
import org.burning.crm.workbench.domain.Customer;
import org.burning.crm.workbench.mapper.ContactsMapper;
import org.burning.crm.workbench.mapper.CustomerMapper;
import org.burning.crm.workbench.service.ContactsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("contactsService")
public class ContactsServiceImpl implements ContactsService {
    @Autowired
    private ContactsMapper contactsMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<Contacts> queryContactsForSaveByName(String name) {
        return contactsMapper.selectContactsForSaveByName(name);
    }

    @Override
    public List<Contacts> queryContactsByCustomerId(String id) {
        return contactsMapper.selectContactsByCustomerId(id);
    }

    @Override
    public void saveCreateContacts(Map<String,Object> map) {
        User user = (User) map.get(Constant.SESSION_USER);
        String customerName = (String) map.get("customerName");
        Customer customer = customerMapper.selectCustomerByName(customerName);
        if (customer == null) {
            customer = new Customer();
            customer.setOwner(user.getId());
            customer.setCreateBy(user.getId());
            customer.setCreateTime(DateUtils.formatDateTime(new Date()));
            customer.setName(customerName);
            customer.setId(UUIDUtils.getUUID());
            customerMapper.insertCustomer(customer);
        }

        Contacts contacts = new Contacts();
        contacts.setCustomerId(customer.getId());
        contacts.setCreateBy(user.getId());
        contacts.setCreateTime(DateUtils.formatDateTime(new Date()));
        contacts.setId(UUIDUtils.getUUID());
        contacts.setOwner((String)map.get("owner"));
        contacts.setSource((String)map.get("source"));
        contacts.setContactSummary((String)map.get("contactSummary"));
        contacts.setMphone((String)map.get("mphone"));
        contacts.setJob((String)map.get("job"));
        contacts.setFullname((String)map.get("fullname"));
        contacts.setEmail((String) map.get("email"));
        contacts.setDescription((String)map.get("description"));
        contacts.setAppellation((String)map.get("appellation"));
        contacts.setAddress((String) map.get("address"));
        contacts.setNextContactTime((String) map.get("nextContactTime"));
        contactsMapper.insertContacts(contacts);
    }

    @Override
    public List<Contacts> queryContactsByConditionForPage(Map<String, Object> map) {
        return contactsMapper.selectContactsByConditionForPage(map);
    }

    @Override
    public int queryCountOfContactsByCondition(Map<String, Object> map) {
        return contactsMapper.selectCountOfContactsByCondition(map);
    }

    @Override
    public int deleteContactsByIds(String[] id) {
        return contactsMapper.deleteContactsByIds(id);
    }

    @Override
    public Contacts queryContactsById(String id) {
        return contactsMapper.selectContactsById(id);
    }

    @Override
    public Contacts queryContactsForDetailById(String id) {
        return contactsMapper.selectContactsForDetailById(id);
    }

    @Override
    public List<Contacts> querySaleviewByConditionForPage(Map<String, Object> map) {
        return contactsMapper.selectSaleviewByConditionForPage(map);
    }

    @Override
    public int queryCountOfSaleviewByCondition(Map<String, Object> map) {
        return contactsMapper.selectCountOfSaleviewByCondition(map);
    }

    @Override
    public boolean sendphone(String content,String customerphone) {
        String testUsername = "chenhongfei"; //在短信宝注册的用户名
        String testPassword = "CHF20010113"; //在短信宝注册的密码
        // 分割手机号码字符串
        String[] phoneNumbers = customerphone.split(",");
        StringBuilder contentJson = new StringBuilder("[");
        for (int i = 0; i < phoneNumbers.length; i++) {
            if (i > 0) {
                contentJson.append(",");
            }
            contentJson.append("您的验证码是1234,５分钟内有效。若非本人操作请忽略此消息");
        }
        contentJson.append("]");
        String httpUrl = "http://api.smsbao.com/sms";
//        String testPhone =phoneNumbers;
        // 构建短信内容
//        String content = smssign +"您的验 接收数组code +"，5分钟内有效。若非本人操作请忽略此消息。"重新构建你的内容
         // 构建请求参数
        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(md5(testPassword)).append("&");
        httpArg.append("m=").append(phoneNumbers).append("&");
        httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));
        // 发送请求并获取结果
        String result = request(httpUrl, httpArg.toString());//返回发送结果，"0"表示发送成功
        System.out.println(result+"================");
        return "".equals(result);
    }
    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }

    @Override
    public void saveEditContacts(Map<String,Object> map) {
        User user = (User) map.get(Constant.SESSION_USER);
        String customerName = (String) map.get("customerName");
        Customer customer = customerMapper.selectCustomerByName(customerName);
        if (customer == null) {
            customer = new Customer();
            customer.setOwner(user.getId());
            customer.setCreateBy(user.getId());
            customer.setCreateTime(DateUtils.formatDateTime(new Date()));
            customer.setName(customerName);
            customer.setId(UUIDUtils.getUUID());
            customerMapper.insertCustomer(customer);
        }

        Contacts contacts = new Contacts();
        contacts.setId((String)map.get("id"));
        contacts.setCustomerId(customer.getId());
        contacts.setEditBy(user.getId());
        contacts.setEditTime(DateUtils.formatDateTime(new Date()));
        contacts.setOwner((String)map.get("owner"));
        contacts.setSource((String)map.get("source"));
        contacts.setContactSummary((String)map.get("contactSummary"));
        contacts.setMphone((String)map.get("mphone"));
        contacts.setJob((String)map.get("job"));
        contacts.setFullname((String)map.get("fullname"));
        contacts.setEmail((String) map.get("email"));
        contacts.setDescription((String)map.get("description"));
        contacts.setAppellation((String)map.get("appellation"));
        contacts.setAddress((String) map.get("address"));
        contacts.setNextContactTime((String) map.get("nextContactTime"));
        contactsMapper.updateContacts(contacts);
    }
}
